

class ImagesController < Controller
  plug :images

  def index e

    if e.params['img']
      image_data = e.params['img'][:tempfile].read

      file = ImageFileRecord.new({})
      file.data = image_data

      #file.data = image.resize(100,100).data
      if !file.save
        raise 'shiiit'
      end
    end

  <<HTML
<form enctype="multipart/form-data" method="post">
  <label>File: </label>
  <input type="file" name="img"/>
  <input type="submit" value="Upload"/>
</form>

<br />
  #{list_images}
<br />

</HTML>
HTML
  end

  def list_images
    ImageFileRecord.all.collect do |i|
      "<img src=\"/images/image?id=#{i.id}\" alt=\"#{i.id}\"/><br />"
    end
  end

  def image e
    if !e.params['id']
      tail_id = e.env[:unprocessed_tail][0].split('.').first
    end
    #p [e.params['width'], e.params['height']]
    begin
      if id = e.params['id'] || tail_id
        if e.params['width']
          image = ImageFileRecord.with_size(
            id.to_i,
            [e.params['width'].to_i, e.params['height'].to_i]
          )
        else
          if id.match /^[0-9]+$/
            image = ImageFileRecord.get(id)
          else
            image = ImageFileRecord.first(:file_name => e.env[:unprocessed_tail][0])
          end
        end
      elsif e.params['file_name']
        image = ImageFileRecord.with_size_named(
          e.params['file_name'],
          [e.params['width'].to_i, e.params['height'].to_i]
        )
      end
    rescue
      warn "Could not get resized image. Fallback to original one."
      warn ([$!] + $!.backtrace).join("\n")

      if e.params['id']
        image = ImageFileRecord.get(e.params['id'].to_i)
      elsif e.params['file_name']
        image = ImageFileRecord.last(:file_name => e.params['file_name'])
      else
        return Rack::Response.new IO.readlines('public/bublifuk/lolcats/invisible-bike.jpg'), 200, {"Content-type" => 'image/jpeg'}
      end
    end

    unless image
      return Rack::Response.new("", 404)
    end

    Rack::Response.new image.data, 200, {
        "Content-type" => 'image/jpeg',

        # images NEVER change, so we tell the
        # client to keep their version and not ask again
        'Cache-control' => 'max-age=31536000',
        'Expires' => (Time.new + 3600*24*365).utc
      }
  end
end
